using CefSharp;
using CefSharp.DevTools.Network;
using CefSharp.Handler;
using System.Runtime.Caching;
//using Microsoft.ClearScript;

namespace Web_rongmeiti_sys.PublishToRongMeiTi
{
    /// <summary>
    /// 页面内容处理，//IResourceRequestHandler
    /// </summary>
    /// 创建时间：2023-5-25 10:04:33。作者：王浩力
    public class MyResourceRequestHandler : ResourceRequestHandler
    {
        /// <summary>
        /// 拦截资源文件，文件内容加载完成时触发
        /// </summary>
        /// <param name="chromiumWebBrowser"></param>
        /// <param name="browser"></param>
        /// <param name="frame"></param>
        /// <param name="request"></param>
        /// <param name="response"></param>
        /// <param name="status"></param>
        /// <param name="receivedContentLength"></param>
        protected override void OnResourceLoadComplete(IWebBrowser chromiumWebBrowser, IBrowser browser, IFrame frame, IRequest request, IResponse response, UrlRequestStatus status, long receivedContentLength)
        {
            LogHelpter.AddLog($"StatusCode={response.StatusCode},url={request.Url}", null, "OnResourceLoadComplete");

            //#获取用户信息接口，url，GET
            //https://xx.xxx.com/api/Common/GetCurrentUserInfo
            if (request.Url.IndexOf("GetCurrentUserInfo", StringComparison.OrdinalIgnoreCase) == -1)
            {
                return;
            }
            var myRequestHandler = chromiumWebBrowser.RequestHandler as MyRequestHandler;
            string cnpc_account = myRequestHandler.Cnpc_account;

            MyResponseFilter responseFilter = FilterManager.GetResponseFilter(request.Identifier) as MyResponseFilter;
            if (responseFilter != null)
            {
                string mimes = "text/plain--text/html,application/json,application/javascript,application/json; charset=utf-8";
                try
                {
                    if (!mimes.Contains(response.MimeType))
                    {
                        return;
                    }
                    ByteArrayContent byteArrayContent = new ByteArrayContent(responseFilter.buffer.ToArray());
                    var task = byteArrayContent.ReadAsStringAsync();
                    task.Wait();
                    var html = task.Result;//json

                    //用户信息存入静态变量
                    GetCurrentUserInfo resultUserInfo = Newtonsoft.Json.JsonConvert.DeserializeObject<GetCurrentUserInfo>(html);
                    if (resultUserInfo.code == 200 && resultUserInfo.result != null)
                    {
                        //写入本地文件保存用户信息
                        ArticlePublishHandler.SaveUserInfoToDiskFile(html, cnpc_account);

                        //滑动过期，十天有效
                        string cacheKey = "userinfo" + cnpc_account;
                        System.Runtime.Caching.MemoryCache.Default.Set(cacheKey, resultUserInfo, new CacheItemPolicy() { SlidingExpiration = TimeSpan.FromMinutes(14400) });
                        //ArticlePublishHandler.publishUser = resultUserInfo;
                    }

#if DEBUG
                    //记录文件内容到本地磁盘，每个url一个文件                    
                    string fileName = GetUrlFileName(request.Url);

                    string dir = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "response");
                    if (!System.IO.Directory.Exists(dir))
                    {
                        System.IO.Directory.CreateDirectory(dir);
                    }
                    string path = Path.Combine(dir, fileName + ".txt");
                    File.WriteAllText(path, html);
#endif

                }
                catch (Exception ex)
                {
                    var ex1 = ex.InnerException ?? ex;
                    LogHelpter.AddLog($"获取响应文本异常，{ex1.Message}", null, "error_response");
                }
            }
        }

        protected override IResponseFilter GetResourceResponseFilter(IWebBrowser chromiumWebBrowser, IBrowser browser, IFrame frame, IRequest request, IResponse response)
        {
            //IResponseFilter responseFilter = FilterManager.GetResponseFilter(request.Identifier);
            //return responseFilter;

            if (request.Url.IndexOf("GetCurrentUserInfo", StringComparison.OrdinalIgnoreCase) >= 0)
            {
                IResponseFilter responseFilter = FilterManager.GetResponseFilter(request.Identifier);
                return responseFilter;
            }
            return null;
        }

        /// <summary>
        /// 根据url获取文件名称
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        /// 创建时间：2023-5-30 09:50:37。作者：王浩力
        public static string GetUrlFileName(string url)
        {
            string fileName = Path.GetFileName(url);
            if (string.IsNullOrWhiteSpace(fileName))
            {
                fileName = url;
            }
            string extend = Path.GetExtension(fileName);

            fileName = fileName.Replace("http://", "").Replace("https://", "").Replace("%", "_")
                   .Replace("?", "_").Replace("/", "_").Replace("=", "_").Replace("&", "_").Replace("#", ".");
            if (string.IsNullOrWhiteSpace(extend))
            {
                fileName = fileName.Length > 50 ? fileName.Substring(0, 50) : fileName;
            }

            //如果文件名太短，添加时间：2023-8-3 11:10:50，王浩力
            if (fileName.Length <= 4)
            {
                fileName = (DateTime.Now.Ticks / 200).ToString();
            }

            //后缀名处理
            if (string.IsNullOrWhiteSpace(extend)
                && (url.LastIndexOf("jpg", StringComparison.CurrentCultureIgnoreCase) > -1
                         || url.LastIndexOf("jpeg", StringComparison.CurrentCultureIgnoreCase) > -1
                      )
                )
            {
                fileName += ".jpg";
            }


            return fileName;
        }

    }
}
